package com.common.widget;

import java.util.Calendar;
import java.util.Date;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.AbstractWheelTextAdapter;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;

import android.content.Context;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.StarAppConst.DATE_TYPE;
import com.common.utils.StarAppUtils;
import com.starappallcommon.R;

/**
 * 日期选择控件
 * <p/>
 * <br>
 * Created 2014-5-5 下午2:54:21
 *
 * @author HuangYK
 * @see
 */
public class WheelDatePicker extends LinearLayout {
    /**
     * 二月最大天数
     */
    private final int maxDayInFeb = 29;

    /**
     * 上下文
     */
    private Context mContext;

    /**
     * 时间
     */
    private Calendar mCalendar;

    /**
     * 月份滚轮
     */
    private WheelView mWvMonth;
    /**
     * 日期滚轮
     */
    private WheelView mWvDay;

    /**
     * 日期滚轮适配器
     */
    private WeekDayAdapter mWeekDayAdapter;

    private MonthAdapter mMonthAdapter;

    /**
     * 文字大小
     */
    private final int TEXT_SIZE = 18;
    /**
     * 当前选中Item的字体颜色
     */
    private static final int CUR_COLOR = 0xFF000000;
    /**
     * 默认Item的字体颜色
     */
    private static final int DEF_COLOR = 0xFFA4A4A4;

    /**
     * 月份列表
     */
    private String[] mMonths;

    /**
     * 是否正在滚动
     */
    private boolean mStartChange = false;
    /**
     * 当前时间
     */
    private long mCurTime;

    /**字体*/
//	private Typeface mTypeface = null;

    /**
     * 是否粗体
     */
    private boolean mIsBlod = false;

    /**
     * 初始化日期滚轮控件
     *
     * @param context 上下文
     */
    public WheelDatePicker(Context context) {
        this(context, null);
    }

    /**
     * 初始化日期滚轮控件
     *
     * @param context 上下文
     * @param attrs   属性
     */
    public WheelDatePicker(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        // 显示的item数量
        final int visibleItemCount = 3;

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.wheel_date_picker, this, true);

        mWvMonth = (WheelView) findViewById(R.id.wvMonth);
        mWvMonth.setVisibleItems(visibleItemCount);
        mWvDay = (WheelView) findViewById(R.id.wvDay);
        mWvDay.setVisibleItems(visibleItemCount);

        OnWheelChangedListener listener = new OnWheelChangedListener() {
            // 延迟操作
            final int delay = 500;

            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                mCurTime = System.currentTimeMillis();
                if (!mStartChange) {
                    mStartChange = true;
                    new Thread() {
                        @Override
                        public void run() {
                            while (mStartChange) {
                                if (System.currentTimeMillis() - mCurTime >= delay) {
                                    mHandler.sendEmptyMessage(0);
                                }
                            }
                        }
                    }.start();
                }
            }
        };

        // month
        mWvMonth.addChangingListener(listener);
        mWvMonth.setCyclic(true);

        // day
        mWvDay.addChangingListener(listener);
        mWvDay.setCyclic(true);
        setDate(Calendar.getInstance());
    }

    /**
     * 更新日期handler
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mCalendar = getDate();
            updateDays();
            mStartChange = false;
        }
    };

    /**
     * 获取日期数据
     *
     * @param @return
     * @return Calendar
     * @n<b>函数名称</b> :getDate
     * @brief
     * @version Ver 1.1
     * @<b>作者</b> : HuangYK
     * @<b>创建时间</b> : 2014-4-21上午10:39:33
     * @see
     */
    public Calendar getDate() {
        Calendar calendar = (Calendar) mCalendar.clone();
        int month = mWvMonth.getCurrentItem();
        calendar.set(Calendar.MONTH, month);
        int day = mWvDay.getCurrentItem() + 1;
        if (month + 1 == 2 && day > maxDayInFeb) {
            day = maxDayInFeb;
        }
        calendar.set(Calendar.DAY_OF_MONTH, day);
        return calendar;
    }

    /**
     * 设置日期
     * <p/>
     * <br>
     * Created 2014-5-5 下午2:55:45
     *
     * @param calendar 日期数据
     * @author : HuangYK
     */
    public void setDate(Calendar calendar) {
        mCalendar = (Calendar) calendar.clone();
        initData(mCalendar);
    }

    /**
     * 设置日期
     * <p/>
     * <br>
     * Created 2014-5-5 下午2:56:00
     *
     * @param date 日期数据
     * @author : HuangYK
     */
    public void setDate(Date date) {
        mCalendar = Calendar.getInstance();
        if (date != null) {
            mCalendar.setTimeInMillis(date.getTime());
        }
        // 暂时默认2012
        final int normalYear = 2012;
        mCalendar.set(Calendar.YEAR, normalYear);

        initData(mCalendar);
    }

    /**
     * 设置字体
     * <p/>
     * <br>Created 2014-8-13 下午7:48:58
     *
     * @param typeface
     * @param isBlod
     * @author :  HuangYK
     */
    public void setTypeface(Typeface typeface, boolean isBlod) {
//		mTypeface = typeface;
        mIsBlod = isBlod;
    }

    /**
     * 初始化日期
     * <p/>
     * <br>
     * Created 2014-5-5 下午2:56:34
     *
     * @param calendar 日期数据
     * @author : HuangYK
     */
    private void initData(Calendar calendar) {
        mMonths = mContext.getResources().getStringArray(R.array.simple_months);
        mMonthAdapter = new MonthAdapter(mContext, mMonths, mCalendar);
        mWvMonth.setViewAdapter(mMonthAdapter);
        mWvMonth.setCurrentItem(mCalendar.get(Calendar.MONTH));

        if (mWvDay.getVisibility() == View.VISIBLE) {
            calendar.set(Calendar.MONTH, mWvMonth.getCurrentItem());

            if (mWeekDayAdapter == null) {
                mWeekDayAdapter = new WeekDayAdapter(mContext, mCalendar);
            } else {
                mWeekDayAdapter.init(calendar,
                        mCalendar.get(Calendar.DAY_OF_MONTH));
            }
            mWvDay.setViewAdapter(mWeekDayAdapter);
        }
        mWvDay.setCurrentItem(mCalendar.get(Calendar.DAY_OF_MONTH) - 1);
    }

    /**
     * 设为当前时间
     * <p/>
     * <br>
     * Created 2014-5-5 下午2:56:42
     *
     * @author : HuangYK
     */
    public void setToNow() {
        setDate(Calendar.getInstance());
    }

    /**
     * 设置格式
     * <p/>
     * <br>
     * Created 2014-5-5 下午2:56:46
     *
     * @param format 格式类型
     * @author : HuangYK
     */
    public void setFormat(int format) {
        switch (format) {
            case DATE_TYPE.month:
                mWvMonth.setVisibility(View.VISIBLE);
                mWvDay.setVisibility(View.GONE);

                break;
            case DATE_TYPE.day:
                mWvMonth.setVisibility(View.VISIBLE);
                mWvDay.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    /**
     * 更新 day滚轮的数据
     * <p/>
     * <br>
     * Created 2014-5-5 下午2:56:54
     *
     * @author : HuangYK
     */
    private void updateDays() {
        mMonthAdapter = new MonthAdapter(mContext, mMonths, mCalendar);
        mWvMonth.setViewAdapter(mMonthAdapter);
        mWvMonth.setCurrentItem(mCalendar.get(Calendar.MONTH));

        if (mWvDay.getVisibility() == View.VISIBLE) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.MONTH, mWvMonth.getCurrentItem());

            if (mWeekDayAdapter == null) {
                mWeekDayAdapter = new WeekDayAdapter(mContext, mCalendar);
            } else {
                mWeekDayAdapter.init(calendar,
                        mCalendar.get(Calendar.DAY_OF_MONTH));
            }
            mWvDay.setViewAdapter(mWeekDayAdapter);
        }
        mWvDay.setCurrentItem(mCalendar.get(Calendar.DAY_OF_MONTH) - 1);

    }

    /**
     * 月份列表适配器
     *
     * @author HuangYK
     * @version v1.1
     * @ClassName MonthAdapter
     * @Function TODO ADD FUNCTION
     * @Reason TODO ADD REASON
     * @Date 2014-4-21 上午10:42:04
     * @see
     */
    private class MonthAdapter extends ArrayWheelAdapter<String> {
        // Index of current item
        int currentItem;
        // Index of item to be highlighted
        int currentValue;

        /**
         * Creates a new instance of MonthAdapter. <br>
         * Created 2014-5-5 下午2:57:01
         *
         * @param context  上下文
         * @param items    item数据
         * @param calendar 当前日期
         */
        public MonthAdapter(Context context, String[] items, Calendar calendar) {
            super(context, items, calendar);
            this.currentValue = mCalendar.get(Calendar.MONTH);
            setTextSize(TEXT_SIZE);
        }

        @Override
        protected void configureTextView(TextView view) {
            super.configureTextView(view);
            if (currentItem == currentValue) {
                view.setTextColor(CUR_COLOR);
            }
//			view.setTypeface(Typeface.SANS_SERIF);
//			if(mTypeface!=null){
            setTypeface(view);
//			}
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            currentItem = index;
            return super.getItem(index, cachedView, parent);
        }
    }

    /**
     * day 列表适配器
     *
     * @author HuangYK
     * @version v1.1
     * @ClassName WeekDayAdapter
     * @Function TODO ADD FUNCTION
     * @Reason TODO ADD REASON
     * @Date 2014-4-21 上午10:42:24
     * @see
     */
    private class WeekDayAdapter extends AbstractWheelTextAdapter {
        // Count of days to be shown
        private int daysCount;
        private int mCurrentDay;

        private final int PADDING = 10;

        /**
         * Creates a new instance of WeekDayAdapter. <br>
         * Created 2014-5-5 下午2:57:18
         *
         * @param context  上下文
         * @param calendar 当前日期
         */
        protected WeekDayAdapter(Context context, Calendar calendar) {
            super(context, R.layout.day_week, NO_RESOURCE);
            init(calendar, calendar.get(Calendar.DAY_OF_MONTH));
            setTextSize(TEXT_SIZE);
        }

        /**
         * 初始化数据
         * <p/>
         * <br>
         * Created 2014-5-5 下午2:57:29
         *
         * @param calendar   当前日期
         * @param currentDay 当前日
         * @author : HuangYK
         */
        private void init(Calendar calendar, int currentDay) {
            mCurrentDay = currentDay;
            if (1 == mWvMonth.getCurrentItem()) {
                daysCount = maxDayInFeb;
            } else {
                daysCount = mCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            }
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {

            View view = super.getItem(index, cachedView, parent);
            Holder holder;
            if (view.getTag() == null) {
                holder = new Holder();
                holder.monthday = (TextView) view.findViewById(R.id.monthday);
                holder.monthday.setTextSize(TEXT_SIZE);
                holder.monthday.setPadding(0, PADDING, 0, PADDING);
                holder.monthday.setTextColor(DEF_COLOR);
                holder.weekday = (TextView) view.findViewById(R.id.weekday);
                holder.weekday.setTextSize(TEXT_SIZE);
                holder.weekday.setTextColor(DEF_COLOR);
//				if(mTypeface!=null){
                setTypeface(holder.monthday);
                setTypeface(holder.weekday);
//				}
            } else {
                holder = (Holder) view.getTag();
            }

            if (index + 1 == mCurrentDay) {
                holder.monthday.setTextColor(CUR_COLOR);
            } else {
                holder.monthday.setTextColor(DEF_COLOR);
            }
//			if (index + 1 < PADDING) {
//				holder.monthday.setText("0" + String.format("%d", index + 1));
//			} else {
            holder.monthday.setText(String.format("%d", index + 1));
//			}

            Calendar newCalendar = (Calendar) mCalendar.clone();
            newCalendar.set(Calendar.DAY_OF_MONTH, index + 1);
            holder.weekday.setVisibility(View.GONE);
            return view;
        }

        @Override
        public int getItemsCount() {
            return daysCount;
        }

        @Override
        protected CharSequence getItemText(int index) {
            return "";
        }

        /**
         * item Holder
         * <p/>
         * <br>
         * Created 2014-5-5 下午2:59:10
         *
         * @author HuangYK
         * @version WheelDatePicker.WeekDayAdapter
         * @see
         */
        private class Holder {
            public TextView monthday;
            public TextView weekday;
        }

        @Override
        protected CharSequence getCurItemText(int index) {
            return null;
        }
    }

    public void setTypeface(TextView textView) {
        StarAppUtils.setViewTypeFace(textView, mIsBlod);
//		textView.setTypeface(mTypeface);
//		if (mIsBlod) {
//			textView.getPaint().setFakeBoldText(true);
//		}
    }
}
